/**
 * Created by PengWei on 2018/7/30.
 */


namespace mengdao {
    import IExtension = mengdao.IExtension;
    import Injector = mengdao.Injector;
    import ContextEvent = mengdao.ContextEvent;
    import TypeIdentifier = mengdao.TypeIdentifier;
    import BaseView = mengdao.BaseView;
    import BaseMediator = mengdao.BaseMediator;

    export class ViewInstaller implements IExtension {

        private _context: Context;
        private _injector: Injector;

        public extend(context: Context): void {
            this._context = context;
            this._injector = context.injector;
            this._context.addEventListener(ContextEvent.NEW_INSTANCE_IN_BIND, this.onNewInBind, this);
        }

        private onNewInBind(e: ContextEvent): void {
            let viewType: TypeIdentifier<BaseView<any>> = e.data;
            /** 只处理BaseView类型的数据 */
            if (!mengdao.isClassExtends(viewType, BaseView)) return;

            let viewInstance  = this._injector.getFromBind(viewType);
            // viewInstance.initialize();

            let mediatorType = this._injector.getFromMap(viewType, this._context);
            let mediatorInstance: BaseMediator = this._injector.getFromBind(mediatorType, this._context);

            if (mediatorInstance) {
                mediatorInstance.view = viewInstance;
                mediatorInstance.initialize();//ask view的initialize会被执行两次
            }
        }
    }
}